// 用户访问行为模块

class userAccess {
  constructor(ctx) {
    ctx = ctx || {};
    if (!ctx || typeof ctx._cloud != "object") {
      throw new Error('初始化用户访问模块时，请传入小程序实例化后的cloud对象');
    }

    this._isTrackNick = ctx.isTrackNick;     //  是否开启明文埋点  true,  false
    this._cloud = ctx._cloud || "";   //  小程序cloud对象   必传
    this._userid = "";    //  用户nick 如若不授权，后台接口则以mixnick传入
    this._device = {};    //  用户当前使用的设备信息
    this._avatar = "";    //  用户头像
    this._code = ctx.code || "";      //  埋点code
    this._emitter = ctx._emitter || "";  // 发送消息对象
    this._network = {};   //  网络状态
    this._authoStatus = false;  //  是否授权

    try {
      //  开启密文埋点
      if(!this._isTrackNick){
        console.log("%c  当前已开启密文埋点模式！" ,  "color: blue");
        this.insert();
        this.pvuv();
      }else{
        console.log("%c  当前已开启明文埋点模式！" ,  "color: blue");
      }

      //  获取客户端网络状态
      my.getNetworkType({
        success: (res) => {
          this._network = res;
        }
      })
      //  获取客户端手机版本信息
      this._device = my.getSystemInfoSync();
    } catch (e) {
      throw new Error('模块错误！--userAccess--初始化失败::' + JSON.stringify(e));
    }
  }

  //  授权
  async onAuthorizate(authoStatus) {
    // 密文埋点开启，不走明文
    if(!this._isTrackNick) return console.log("%c  当前已开启密文埋点模式！" ,  "color: blue");

    // 防止重复埋点
    if(this._authoStatus) return;
    this._authoStatus = true;

    if (authoStatus) {
      this.getNick();
    } else {
      //  开启授权   授权失败
      console.log("%c  授权失败，不能进行明文埋点!" ,  "color: red");
    }
  }

  //  获取用户头像和昵称
  async getNick() {
    let _this = this;
    my.getAuthUserInfo({
      success: (userInfo) => {
        _this._userid = userInfo.nickName || "";
        _this._avatar = userInfo.avatar || "";
        _this.insert();
        _this.pvuv();
      }
    })
  }

  // pvuv埋点
  async pvuv() {
    if (typeof this._cloud != "object") {
      return {
        success: false,
        data: {},
        errorCode: "1001",
        errorMessage: "_cloud不是一个方法，请在初始化方法中传入小程序的实例化后的cloud对象！"
      }
    }

    if (!this._code) {
      console.log("%c  pvuv埋点--请传入项目埋点ID！" ,  "color: red");
      return {
        success: false,
        data: {},
        errorCode: "1002",
        errorMessage: "请传入项目埋点ID！"
      }
    }

    return await this._cloud.function.invoke('dataTrackCloud', { code: this._code }, 'pvuv')
  }

  // 自定义埋点
  async custom(customType) {
    if (typeof this._cloud != "object") {
      return {
        success: false,
        data: {},
        errorCode: "1001",
        errorMessage: "_cloud不是一个方法，请在初始化方法中传入小程序的实例化后的cloud对象！"
      }
    }

    if (!this._code) {
      console.log("%c  自定义埋点--请配置项目埋点ID！" ,  "color: red");
      return {
        success: false,
        data: {},
        errorCode: "1002",
        errorMessage: "自定义埋点--请配置项目埋点ID！"
      }
    }

    if (!customType) {
      console.log("%c  自定义埋点--请传入自定义埋点信息！" ,  "color: red");
      return {
        success: false,
        data: {},
        errorCode: "1003",
        errorMessage: "自定义埋点--请传入自定义埋点信息!"
      }
    }

    return await this._cloud.function.invoke('dataTrackCloud', { code: this._code, customType: customType }, 'custom')
  }

  //  新增用户信息
  async insert(obj) {
    try {
      // 调用判断
      if (typeof this._cloud != "object") {
        return {
          success: false,
          data: {},
          errorCode: "1001",
          errorMessage: "_cloud不是一个方法，请在初始化方法中传入小程序的实例化后的cloud对象！"
        }
      }
      return await this._cloud.function.invoke('userAccessCloud', {
        // userid: this._userid,
        avatar: this._avatar,
        appName: this._device.app || "淘宝",
        appVersion: this._device.version || "0.0.0",
        phonePlatform: this._device.platform || "未知",
        phoneModel: this._device.model || "未知",
        phoneSystem: this._device.system || "未知",
        network: JSON.stringify(this._network),
        network: JSON.stringify(this._device),
        ...obj
      }, 'insert')
    } catch (e) {
      return {
        success: false,
        data: {},
        errorCode: "9001",
        errorMessage: "模块错误！--userAccess--insert::" + JSON.stringify(e)
      }
    }
  }

  //  获取用户信息  
  async get() {
    try {
      // 调用判断
      if (typeof this._cloud != "object") {
        return {
          success: false,
          data: {},
          errorCode: "1001",
          errorMessage: "_cloud不是一个方法，请在初始化方法中传入小程序的实例化后的cloud对象！"
        }
      }
      // 调用云函数
      return await this._cloud.function.invoke('userAccessCloud', {
        userid: this._userid
      }, 'get');
    } catch (e) {
      return {
        success: false,
        data: {},
        errorCode: "9001",
        errorMessage: "模块错误！--userAccess--get::" + JSON.stringify(e)
      }
    }
  }

  //  新增 用户信息字段
  async insertKey(obj) {
    try {
      // 调用判断
      obj = obj || {};
      if (typeof this._cloud != "object") {
        return {
          success: false,
          data: {},
          errorCode: "1001",
          errorMessage: "_cloud不是一个方法，请在初始化方法中传入小程序的实例化后的cloud对象！"
        }
      }
      if (Object.keys(obj).length == 0) {
        return {
          success: false,
          data: {},
          errorCode: "1002",
          errorMessage: "请传入所要新增的字段对象！"
        }
      }

      // 调用云函数
      return await this._cloud.function.invoke('userAccessCloud', obj, 'insertKey');
    } catch (e) {
      return {
        success: false,
        data: {},
        errorCode: "9001",
        errorMessage: "模块错误！--userAccess--insertKey::" + JSON.stringify(e)
      }
    }
  }

  //  消息发送器
  async sendMsg(msg) {
    if (!this._emitter) {
      return console.log("_emitter对象不存在，请在初始化时传入");
    }
    let msgstr = typeof msg == "string" ? msg : JSON.stringify(msg);

    this._emitter.emit("logger-topic", { origin: "userAccess.js", data: msgstr });
  }

}

module.exports = exports.userAccess = userAccess;